/*
	This file is part of "Ants on the web".

    "Ants on the web" is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    "Ants on the web" is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with "Ants on the web".  If not, see <http://www.gnu.org/licenses/>.
*/

package org.utc.ia04.antsontheweb.knowledgeBase;

import org.utc.ia04.antsontheweb.utilities.KnowledgeBaseRequest;
import org.utc.ia04.antsontheweb.utilities.Requete;
import org.utc.ia04.antsontheweb.utilities.RequeteException;

import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;

/**
 * @author Ronan
 * @category Behaviour
 * Behaviour associated to KnowledgeBaseAgent
 */
public class ReceiveMessage extends CyclicBehaviour
{
	//serialVersionUID
	private static final long serialVersionUID = -8002892640171967609L;

	public void action()
	{
		ACLMessage message = myAgent.receive();
		if(message == null)
			block();
		else
		{
			try
			{
				Requete query = Requete.deserialize_withException(message.getContent(), myAgent, message);
				analyseQuery(query, message);	
			}
			catch (RequeteException e) { errorOccured(KnowledgeBaseAgent.UNFORMATTED, message); }
		}
	}
	
	private void analyseQuery(Requete query, ACLMessage message)
	{
		KnowledgeBaseRequest deserializedQuery = KnowledgeBaseRequest.deserialize(query.getContent());
		if(deserializedQuery == null)
		{
			errorOccured(KnowledgeBaseAgent.UNFORMATTED, message);
			return;
		}
		
		int websiteType = deserializedQuery.getWebsiteType();
		if(websiteType < 0 || websiteType >= KnowledgeBaseAgent.LAST)
		{
			errorOccured(KnowledgeBaseAgent.UNKNOWN_WEBSITE_TYPE, message);
			return;
		}
		
		switch(query.getType())
		{
			case Requete.KB_LEARN :
				((KnowledgeBaseAgent)myAgent).learn(websiteType, deserializedQuery.getKeywords(), message);
				break;
			case Requete.KB_GIVE_WEBSITE_TYPE :
				//DEBUG
				//System.out.println(myAgent.getName()+" receive a GIVE_WEBSITE_TYPE query." );
				((KnowledgeBaseAgent)myAgent).giveWebsiteType(websiteType, deserializedQuery.getKeywords(), message);
				break;
			default:
				errorOccured(KnowledgeBaseAgent.UNFORMATTED, message);
				break;
		}
	}
	
	private void errorOccured(String log, ACLMessage message)
	{
		ACLMessage answer = message.createReply();
		answer.setPerformative(ACLMessage.FAILURE);
		
		Requete r = new Requete(Requete.KB_ERROR, log);
		answer.setContent(r.serialize());

		myAgent.send(answer);
	}
}
